/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package gestion;

import java.awt.Component;
import java.awt.event.ItemEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import static javax.swing.SwingConstants.CENTER;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import otros.Fecha;
import otros.Util;
import tablas.DineroContado;
import tablas.FacturasAlbaranes;

/**
 *
 * @author FERRETERIA
 */
public class FVentasDia extends javax.swing.JInternalFrame {
    boolean fuera;
    boolean guardar;
    int filaSel;
    int descuento;
    float total;
    int idDinero;
       
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
    public FVentasDia() {
        initComponents();
        AnchoColumnas();
        tabla.setColumnSelectionAllowed(false);
        String []fecha = new Fecha().getFecha().split("-");
        txtDia.setText(fecha[0]);
        txtMes.setText(fecha[1]);
        txtAño.setText(fecha[2]);
        ActualizarTabla();
    }

    private void AnchoColumnas() {
        DefaultTableColumnModel colModel = (DefaultTableColumnModel)tabla.getColumnModel();
        TableColumn col = colModel.getColumn(0);        
        col.setPreferredWidth(150);
        col = colModel.getColumn(1);
        col.setPreferredWidth(320);
        
        bConvertir.setEnabled(false);
        guardar = true;
    }
    
    private void ActualizarTabla() {                    
        int dia = Integer.parseInt(txtDia.getText().isEmpty()? "0" : txtDia.getText());
        int mes = Integer.parseInt(txtMes.getText().isEmpty()? "0" : txtMes.getText());
        int año = Integer.parseInt(txtAño.getText().isEmpty()? "0" : txtAño.getText());
        
        DefaultTableModel datos = FacturasAlbaranes.getTabla(true,false, 0, 0, 0, dia, mes, año);
        tabla.setModel(datos);              
        tabla.getColumnModel().getColumn(0).setCellRenderer(new tableCellRender.Id(filaSel, fuera,0));
        tabla.getColumnModel().getColumn(1).setCellRenderer(new tableCellRender.Texto(filaSel, fuera));
        tabla.getColumnModel().getColumn(2).setCellRenderer(new tableCellRender.Precio(filaSel, fuera));
        tabla.getColumnModel().getColumn(3).setCellRenderer(new tableCellRender.Fecha(filaSel, fuera));
        tabla.getColumnModel().getColumn(4).setCellRenderer(new tableCellRender.Texto(filaSel, fuera));
        AnchoColumnas();
        
        HallarTotal();
    }
     
    private void HallarTotal() {
        total = 0;
        String des = "";
        for(int i = 0; i < tabla.getRowCount(); i++) {
            total += Float.parseFloat(tabla.getValueAt(i, 2).toString());
            if((tabla.getValueAt(i, 4) != null) && des.isEmpty() && !tabla.getValueAt(i, 4).toString().isEmpty()) {
                des =""+DineroContado.getDescuento(tabla.getValueAt(i, 4).toString());
                guardar = false;
                idDinero = Integer.parseInt(tabla.getValueAt(i, 4).toString());
            }
        }
        txtTotal.setText(Util.getFormatPrecio(total,2));
        
        if (!des.isEmpty()) txtDescuento.setText(des+"%");
        else { 
            txtDescuento.setText("");
            txtDinero.setText("");
        }
        
        if (!txtDescuento.getText().isEmpty()) {
            float desc = Float.parseFloat(txtDescuento.getText().replace("%",""));
            txtDescuento.setText(desc+"%");
            txtDinero.setText(Util.getFormatPrecio(total * ((float)desc/100),2));
        }
    }
    
    private void Guardar () {
        try {
            float desc = Float.parseFloat(txtDescuento.getText().replace("%",""));
            String fecha = txtAño.getText() + "-" + txtMes.getText() + "-" + txtDia.getText();
            if (guardar) {
                String [] datos = {fecha, ""+total, ""+desc,
                                   txtDinero.getText().replace(",",".").replace("€", "")};
                idDinero = DineroContado.guardar(datos, guardar);
            } else {
                String [] datos = {fecha, ""+total, ""+desc,
                                   txtDinero.getText().replace(",",".").replace("€", ""), 
                                   ""+idDinero};
                DineroContado.guardar(datos, guardar);
            }
            FacturasAlbaranes.RealizarDescuentoDia(fecha,idDinero);
            ActualizarTabla();
        } catch(Exception e) {
            ;
        }    
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtDia = new javax.swing.JFormattedTextField();
        jLabel3 = new javax.swing.JLabel();
        txtMes = new javax.swing.JFormattedTextField();
        bBuscar = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        txtAño = new javax.swing.JFormattedTextField();
        jPanel2 = new javax.swing.JPanel();
        bConvertir = new javax.swing.JButton();
        txtTotal = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtDescuento = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtDinero = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Gestion Ventas al Contado");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/img/icono2.png"))); // NOI18N
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jScrollPane1.setMinimumSize(new java.awt.Dimension(250, 250));
        jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 250));

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Cliente", "Total", "Fecha"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabla.setColumnSelectionAllowed(true);
        tabla.getTableHeader().setReorderingAllowed(false);
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                tablaMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                tablaMouseExited(evt);
            }
        });
        tabla.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                tablaMouseMoved(evt);
            }
        });
        jScrollPane1.setViewportView(tabla);
        tabla.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        if (tabla.getColumnModel().getColumnCount() > 0) {
            tabla.getColumnModel().getColumn(0).setResizable(false);
            tabla.getColumnModel().getColumn(1).setResizable(false);
            tabla.getColumnModel().getColumn(2).setResizable(false);
            tabla.getColumnModel().getColumn(3).setResizable(false);
        }

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        getContentPane().add(jScrollPane1, gridBagConstraints);

        jPanel1.setMinimumSize(new java.awt.Dimension(400, 70));
        jPanel1.setPreferredSize(new java.awt.Dimension(400, 70));
        jPanel1.setLayout(new java.awt.GridBagLayout());

        jLabel1.setText("Criterios de busqueda:   ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        jPanel1.add(jLabel1, gridBagConstraints);

        jLabel2.setText("Dia");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
        jPanel1.add(jLabel2, gridBagConstraints);

        txtDia.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("00"))));
        txtDia.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtDia.setMinimumSize(new java.awt.Dimension(25, 20));
        txtDia.setPreferredSize(new java.awt.Dimension(25, 20));
        txtDia.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtDiaMouseClicked(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 25, 0, 0);
        jPanel1.add(txtDia, gridBagConstraints);

        jLabel3.setText("Mes");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 29);
        jPanel1.add(jLabel3, gridBagConstraints);

        txtMes.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("00"))));
        txtMes.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtMes.setMinimumSize(new java.awt.Dimension(25, 20));
        txtMes.setPreferredSize(new java.awt.Dimension(25, 20));
        txtMes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtMesMouseClicked(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 80, 0, 0);
        jPanel1.add(txtMes, gridBagConstraints);

        bBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/buscar.png"))); // NOI18N
        bBuscar.setMinimumSize(new java.awt.Dimension(61, 61));
        bBuscar.setPreferredSize(new java.awt.Dimension(61, 61));
        bBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bBuscarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        jPanel1.add(bBuscar, gridBagConstraints);

        jLabel4.setText("Año");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 29);
        jPanel1.add(jLabel4, gridBagConstraints);

        txtAño.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("0000"))));
        txtAño.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtAño.setToolTipText("yyyy");
        txtAño.setMinimumSize(new java.awt.Dimension(25, 20));
        txtAño.setPreferredSize(new java.awt.Dimension(35, 20));
        txtAño.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtAñoMouseClicked(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 30, 0, 0);
        jPanel1.add(txtAño, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 175;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(11, 10, 0, 10);
        getContentPane().add(jPanel1, gridBagConstraints);

        jPanel2.setPreferredSize(new java.awt.Dimension(60, 60));
        jPanel2.setLayout(new java.awt.GridBagLayout());

        bConvertir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/guardar.png"))); // NOI18N
        bConvertir.setMinimumSize(new java.awt.Dimension(60, 60));
        bConvertir.setPreferredSize(new java.awt.Dimension(60, 60));
        bConvertir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bConvertirActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 10;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        jPanel2.add(bConvertir, gridBagConstraints);

        txtTotal.setEditable(false);
        txtTotal.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtTotal.setMinimumSize(new java.awt.Dimension(100, 20));
        txtTotal.setPreferredSize(new java.awt.Dimension(100, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridheight = 2;
        jPanel2.add(txtTotal, gridBagConstraints);

        jLabel5.setText("Total del dia");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
        jPanel2.add(jLabel5, gridBagConstraints);

        txtDescuento.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtDescuento.setPreferredSize(new java.awt.Dimension(60, 20));
        txtDescuento.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtDescuentoMouseClicked(evt);
            }
        });
        txtDescuento.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtDescuentoKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        jPanel2.add(txtDescuento, gridBagConstraints);

        jLabel6.setText("Descuento del dia");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        jPanel2.add(jLabel6, gridBagConstraints);

        txtDinero.setEditable(false);
        txtDinero.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtDinero.setMinimumSize(new java.awt.Dimension(100, 20));
        txtDinero.setPreferredSize(new java.awt.Dimension(100, 20));
        txtDinero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtDineroActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 5;
        gridBagConstraints.gridheight = 2;
        jPanel2.add(txtDinero, gridBagConstraints);

        jLabel7.setText("Dinero");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 5;
        gridBagConstraints.gridy = 0;
        jPanel2.add(jLabel7, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
        getContentPane().add(jPanel2, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseClicked
        int fila = tabla.getSelectedRow();
        if (fila > 0) {
            if (evt.isMetaDown()) { 
                FacturasAlbaranes.RealizarDescuentoDia(tabla.getValueAt(fila, 0).toString());
                ((DefaultTableModel)tabla.getModel()).removeRow(fila);
                HallarTotal();
            }
            else if (evt.getClickCount() == 2) {
                FTPV tpv = new FTPV();
                this.getParent().add(tpv);
                Principal.centrarFrame(tpv);
                tpv.show();
                tpv.cargar(""+tabla.getValueAt(fila, 0),0);
            }
        }
    }//GEN-LAST:event_tablaMouseClicked

    private void tablaMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseExited
        fuera = true;
    }//GEN-LAST:event_tablaMouseExited

    private void tablaMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseEntered
        fuera = false;
    }//GEN-LAST:event_tablaMouseEntered

    private void tablaMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseMoved
        JTable aTable =  (JTable)evt.getSource();
        if (!fuera) {
            filaSel = aTable.rowAtPoint(evt.getPoint());
        }
    }//GEN-LAST:event_tablaMouseMoved

    private void bBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBuscarActionPerformed
        ActualizarTabla();
    }//GEN-LAST:event_bBuscarActionPerformed

    private void txtDiaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtDiaMouseClicked
        txtDia.selectAll();
    }//GEN-LAST:event_txtDiaMouseClicked

    private void txtMesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtMesMouseClicked
        txtMes.selectAll();
    }//GEN-LAST:event_txtMesMouseClicked

    private void bConvertirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bConvertirActionPerformed
        if(JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null, "¿Esta seguro de esta Operacion?","Aplicar Descuento", JOptionPane.OK_CANCEL_OPTION)) {
           Guardar();
        }
    }//GEN-LAST:event_bConvertirActionPerformed

    private void txtAñoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtAñoMouseClicked
        txtAño.selectAll();
    }//GEN-LAST:event_txtAñoMouseClicked

    private void txtDineroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDineroActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtDineroActionPerformed

    private void txtDescuentoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtDescuentoMouseClicked
        txtDescuento.selectAll();
    }//GEN-LAST:event_txtDescuentoMouseClicked

    private void txtDescuentoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescuentoKeyReleased
       if (evt.getKeyCode() == 10) {
           try {
                float desc = Float.parseFloat(txtDescuento.getText().replace("%",""));
                txtDescuento.setText(desc+"%");
                txtDinero.setText(Util.getFormatPrecio(total * ((float)desc/100),2));
                bConvertir.setEnabled(true);
           } catch (Exception e) {
               txtDescuento.setText("");
               bConvertir.setEnabled(false);
           }
        }
    }//GEN-LAST:event_txtDescuentoKeyReleased

         
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bBuscar;
    private javax.swing.JButton bConvertir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabla;
    private javax.swing.JFormattedTextField txtAño;
    private javax.swing.JTextField txtDescuento;
    private javax.swing.JFormattedTextField txtDia;
    private javax.swing.JTextField txtDinero;
    private javax.swing.JFormattedTextField txtMes;
    private javax.swing.JTextField txtTotal;
    // End of variables declaration//GEN-END:variables
}
